package tt.dz.biz.service.batchpay;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import tt.dz.biz.dao.batchpay.LiabilitiesDAO;
import tt.dz.biz.dao.trade.TradeDAOImpl;
import tt.dz.biz.service.common.CommonService;
import tt.dz.common.BusinessException;
import tt.dz.common.DZStringUtil;
import tt.dz.common.DateUtil;
import tt.dz.common.DzConstants;
import tt.dz.common.DzConstants.accountingState;
import tt.dz.common.DzConstants.commonValid;
import tt.dz.common.DzConstants.payState;
import tt.dz.common.DzConstants.userType;
import tt.dz.common.DzErrorCode;
import tt.dz.common.DzErrorCode.CommonErrorCode;
import tt.dz.common.DzErrorCode.TranErrorCode;
import tt.dz.common.LogUtil;
import tt.dz.vo.MerchLiabilitiesMonthVO;
import tt.dz.vo.OrderServiceVO;
import tt.dz.vo.TranInfoVO;

@Service("liabilitiesService")
public class LiabilitiesService
{
  @Resource(name="commonService")
  private CommonService commonService;
  @Resource(name="liabilitiesDAO")
  private LiabilitiesDAO liabilitiesDAO;
  @Resource(name="tradeDAO")
  private TradeDAOImpl tradeDAO;
  
  public void saveMerchantLiabilities()
    throws Exception
  {
    try
    {
      Date accountingDate = this.commonService.getAccountingDate();
      Date thedayOfLastMonth = DateUtil.getCurrentDadOfLastMonth(accountingDate);
      List<MerchLiabilitiesMonthVO> l = queryLiabilitiesByMonthAndMerchant(DateUtil.formatyyyyMM(thedayOfLastMonth), null);
      if (CollectionUtils.isNotEmpty(l)) {
        this.liabilitiesDAO.deleteLiabilities(DateUtil.formatyyyyMM(thedayOfLastMonth));
      }
      String startDate = DateUtil.getStringByYMD(DateUtil.getFirstDayOfMonth(thedayOfLastMonth));
      String endDate = DateUtil.getStringByYMD(DateUtil.getLastDayOfMonth(thedayOfLastMonth));
      
      List<MerchLiabilitiesMonthVO> liabilityList = this.liabilitiesDAO.sumLiabilities(startDate, endDate);
      if (CollectionUtils.isNotEmpty(liabilityList))
      {
        Date now = this.commonService.getDBCurrentTime();
        String liabilitiesSeq = null;
        for (Iterator localIterator = liabilityList.iterator(); localIterator.hasNext();)
        {
        	MerchLiabilitiesMonthVO   merchLiabilitiesMonthVO = (MerchLiabilitiesMonthVO)localIterator.next();
       long   seq = this.commonService.querySequence("seq_merch_liabilities_month");
          liabilitiesSeq = DZStringUtil.getFixedLengthString(20, String.valueOf(seq));
          merchLiabilitiesMonthVO.setLiabilitiesSeq(liabilitiesSeq);
          merchLiabilitiesMonthVO.setIsValid(DzConstants.commonValid.VALID.value());
          merchLiabilitiesMonthVO.setCreatedTime(now);
          merchLiabilitiesMonthVO.setAccountingDate(accountingDate);
          merchLiabilitiesMonthVO.setState(DzConstants.payState.WAITING_FOR_PAYING.value());
        }
        int[] rs = this.liabilitiesDAO.insertMerchLiabilities(liabilityList);
//        MerchLiabilitiesMonthVO merchLiabilitiesMonthVO = rs;
        long seq = rs.length;
        for (int l1 = 0; l1 < seq; l1++)
        {
          int i = rs[l1];
          if (i <= 0) {
            throw new BusinessException(DzErrorCode.CommonErrorCode.SAVE_ERROR.value(), "保存运营商的应付款数据异常", "保存运营商的应付款数据异常");
          }
        }
      }
    }
    catch (Exception e)
    {
      LogUtil.error("统计账务日期上月运营商的应付款", e);
      throw e;
    }
  }
  
  public List<MerchLiabilitiesMonthVO> queryLiabilitiesByMonthAndMerchant(String yyyyMM, String merchantCode)
    throws Exception
  {
    try
    {
      return this.liabilitiesDAO.queryLiabilitiesByMonthAndMerchant(yyyyMM, merchantCode);
    }
    catch (Exception e)
    {
      LogUtil.error("查询运营商应付款异常", e);
      throw e;
    }
  }
  
  public List<OrderServiceVO> querySettlementServiceList(String subSubjectNo)
    throws Exception
  {
    try
    {
      return this.liabilitiesDAO.querySettlementServiceBySubjectNo(subSubjectNo);
    }
    catch (Exception e)
    {
      LogUtil.error("根据关联的科目,查询虚拟服务（结算服务）异常，科目编码subSubjectNo为：" + subSubjectNo, e);
      throw e;
    }
  }
  
  public void savePayLiabilities(MerchLiabilitiesMonthVO merchLiabilitiesMonthVO, TranInfoVO tranInfo)
    throws Exception
  {
    try
    {
      String currentDate = DateUtil.getDateFormatter();
      String seqNo = DZStringUtil.getFixedLengthString(8, String.valueOf(this.tradeDAO.querySequence("seq_trade_no")));
      String tradeNo = String.valueOf(DzConstants.userType.MERCHANT_CUSTOMER.value()) + tranInfo.getAppId() + currentDate + seqNo;
      
      merchLiabilitiesMonthVO.setState(DzConstants.payState.PAY_SUCCESS.value());
      merchLiabilitiesMonthVO.setPayAccountDate(this.commonService.getAccountingDate());
      merchLiabilitiesMonthVO.setTradeNo(tradeNo);
      int n = this.liabilitiesDAO.updateLiabilities(merchLiabilitiesMonthVO);
      if (n != 1) {
        throw new BusinessException(DzErrorCode.CommonErrorCode.SAVE_ERROR.value(), "更新应付款状态为付款完成失败。参数merchLiabilitiesMonthVO为：" + merchLiabilitiesMonthVO.toString(), "更新应付款状态为付款完成失败。参数merchLiabilitiesMonthVO为：" + merchLiabilitiesMonthVO.toString());
      }
      tranInfo.setTradeNo(tradeNo);
      tranInfo.setAccountingDate(this.commonService.getAccountingDate());
      tranInfo.setPlatTime(this.commonService.getDBCurrentTime());
      tranInfo.setAccountState(DzConstants.accountingState.WAIT_FOR_ACCOUNTING.value());
      n = this.tradeDAO.insertTranInfo(tranInfo);
      if (n != 1) {
        throw new BusinessException(DzErrorCode.TranErrorCode.SAVE_TRAN_INFO_FAIL.value(), "保存结算交易信息失败", "保存结算交易信息失败");
      }
    }
    catch (Exception e)
    {
      LogUtil.error("运营商应付款结算异常，参数merchLiabilitiesMonthVO为：" + merchLiabilitiesMonthVO + ",tranInfo为：" + tranInfo, e);
      throw e;
    }
  }
}
